package com.gmss.crawler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmss.crawler.module.honor.domain.Honor;
import com.gmss.crawler.module.honor.service.IHonorService;
import com.gmss.crawler.module.person.domain.PersonInfo;
import com.gmss.crawler.module.person.service.IPersonInfoService;
import com.gmss.crawler.module.resume.domain.Resume;
import com.gmss.crawler.module.resume.service.IResumeService;
import com.gmss.crawler.module.social.domain.Social;
import com.gmss.crawler.module.social.service.ISocialService;
import com.gmss.crawler.utils.CommonUtils;
import com.gmss.crawler.utils.CrawlerCommonUtils;
import com.gmss.crawler.utils.DateUtils;
import com.gmss.crawler.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 中国院士馆信息爬取
 */
@Slf4j
@Service
public class PersonalHomeService {

    @Resource
    private IPersonInfoService iPersonInfoService;
    @Resource
    private IResumeService iResumeService;
    @Resource
    private IHonorService iHonorService;
    @Resource
    private ISocialService iSocialService;

    public final String index = "https://www.cae.cn/cae/html/main/col48/column_48_1.html";
    public static final String url = "https://www.cae.cn";

    // 首页
    public static final String indexPath = "http://ysg.ckcest.cn/html/details/[]/index.html";
    // 主要学历
    public static final String educationPath = "https://ysg.ckcest.cn/html/details/subnav/content/[]/detail_grxx_zyxl";
    // 主要经历
    public static final String experiencePath = "https://ysg.ckcest.cn/html/details/subnav/content/[]/detail_grxx_zyjl";
    // 重要任职/主要任职
    public static final String dutiesPath = "https://ysg.ckcest.cn/html/details/subnav/content/[]/detail_grxx_zyrz";
    // 科技奖项
    public static final String prizePath = "https://ysg.ckcest.cn/html/details/subnav/content/[]/detail_cjgx_kjjx";
    // 荣誉称号
    public static final String honorPath = "https://ysg.ckcest.cn/html/details/subnav/content/[]/detail_cjgx_rych";

    public static void main(String[] args) {

        PersonInfo personInfo = new PersonInfo().builder().id(1816L).name("孙丽丽").build();
        // 8158
        new PersonalHomeService().getResume(personInfo, "http://ysg.ckcest.cn/html/details/8158/index.html");

//        2676
//        //new PersonalHomeService().getPersonalHome();
        //      PersonInfo personInfo = new PersonInfo();
////        new PersonalHomeService().getCaePersonalInfo(personInfo);
//        new PersonalHomeService().parseIndex(personInfo, "https://ysg.ckcest.cn/html/details/632/index.html");
//        new PersonalHomeService().parsePrize(personInfo,"https://ysg.ckcest.cn/html/details/subnav/content/61/detail_cjgx_kjjx", 0);
//        new PersonalHomeService().parseHonor(personInfo,"https://ysg.ckcest.cn/html/details/subnav/content/297/detail_cjgx_rych", 1);
    }

    /**
     * 更新院士个人信息
     * https://ysg.ckcest.cn/html/index.html
     *
     * @return
     */
    public void getCaePersonalInfo(PersonInfo personInfo, String value) {
        try {
//            Map<String, String> fileLinesMap = FileUtil.readFileLines("/crawlerUrlFile/caePersonal.txt", ";");
//            if (fileLinesMap.containsKey(personInfo.getName())) {
            log.info("更新院士个人信息:{}", personInfo.getName());
            Thread.sleep(CommonUtils.randomRange(100, 500));
//                String value = fileLinesMap.get(personInfo.getName());

            String indexPathUrl = RegexUtils.replaceData(indexPath, RegexUtils.ALL_ZHONG_REGEX, value);
            String educationPathUrl = RegexUtils.replaceData(educationPath, RegexUtils.ALL_ZHONG_REGEX, value);
            String experiencePathUrl = RegexUtils.replaceData(experiencePath, RegexUtils.ALL_ZHONG_REGEX, value);
            String dutiesPathUrl = RegexUtils.replaceData(dutiesPath, RegexUtils.ALL_ZHONG_REGEX, value);
            String prizePathUrl = RegexUtils.replaceData(prizePath, RegexUtils.ALL_ZHONG_REGEX, value);
            String honorPathUrl = RegexUtils.replaceData(honorPath, RegexUtils.ALL_ZHONG_REGEX, value);

            // 个人信息
            parseIndex(personInfo, indexPathUrl);
            // 主要学历
            parseEducation(personInfo, educationPathUrl);
            // 主要经历
            parseExperience(personInfo, experiencePathUrl);
            // 重要任职/主要任职
            parseDuties(personInfo, dutiesPathUrl);
            // 科技奖项
            parsePrize(personInfo, prizePathUrl, 0);
            // 荣誉称号
            parseHonor(personInfo, honorPathUrl, 1);
            // 人生经历
            getResume(personInfo, indexPathUrl);
//            }
        } catch (Exception e) {
            log.error("Exception : {}", e);
        }

//        parseHonor(null ,null, 1);
//        parsePrize(null,"");
//        parseDuties(null,"");
//        parseExperience(null, "");
//        parseEducation(null, "");
    }

    private void parseHonor(PersonInfo personInfo, String url, Integer type) {
        if (null == personInfo)
            personInfo = new PersonInfo();
//        url = "https://ysg.ckcest.cn/html/details/subnav/content/632/detail_cjgx_rych";
        Document doc = CrawlerCommonUtils.getDocument(url);
        if (null == doc)
            return;
        String allHonors = doc.select(".content-box .title").text();
        allHonors = allHonors.replaceAll("：", ":");
        String[] honors = allHonors.split(" ");
        List<Honor> list = new ArrayList<>();
        for (int i = 0; i < honors.length; i++) {
            Honor honorEntity = new Honor().builder().personId(personInfo.getId()).type(type).build();
            if (StringUtils.isNotBlank(honors[i])) {
                String[] honor = honors[i].split(":");
                if (honor.length > 1) {
                    String honorDate = "";
                    try {
                        honorDate = DateUtils.handleDate(honor[0]);
                    } catch (Exception e) {
                        honorDate = honor[0];
                    }
                    honorEntity.setHonorDate(honorDate);
                    getLevel(honorEntity, honor[1]);
                } else {
//                    map.put("honor", honors[i]);
                    getLevel(honorEntity, honors[i]);
                }
                list.add(honorEntity);
            }

        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = list.size() - 1; i >= 0; i--) {
                LambdaQueryWrapper<Honor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(Honor::getPrizeName, list.get(i).getPrizeName());
                queryWrapper.eq(Honor::getPersonId, list.get(i).getPersonId());
//                queryWrapper.eq(Honor::getType, type);
                List<Honor> queryList = iHonorService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(queryList) && queryList.size() > 0) {
                    list.get(i).setId(queryList.get(0).getId());
                }
            }
            iHonorService.saveOrUpdateBatch(list);
        }
    }

    private void parsePrize(PersonInfo personInfo, String url, Integer type) {
//        url = "https://ysg.ckcest.cn/html/details/subnav/content/621/detail_cjgx_kjjx";
        Document doc = CrawlerCommonUtils.getDocument(url);
        if (null == doc)
            return;
        Elements titleElements = doc.select(".kj_main .content-box").select(".title");
        List<Honor> list = new ArrayList<>();
        for (Element titleElement : titleElements) {
            Map<String, String> map = new LinkedHashMap<>();
            Honor honor = new Honor().builder().personId(personInfo.getId()).type(type).build();
            String[] split = titleElement.text().split(" ");
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 1; i < split.length; i++) {
                String honorDate = "";
                try {
                    honorDate = DateUtils.handleDate(split[0]);
                } catch (Exception e) {
                    stringBuilder.append(split[0]).append(",");
                }
                honor.setHonorDate(honorDate);
                if (i == split.length - 1) {
                    stringBuilder.append(split[i]);
                } else {
                    stringBuilder.append(split[i]).append(",");
                }
                honor.setPrizeName(stringBuilder.toString());
                getLevel(honor, stringBuilder.toString());
            }
            list.add(honor);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = list.size() - 1; i >= 0; i--) {
                LambdaQueryWrapper<Honor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(Honor::getPrizeName, list.get(i).getPrizeName());
                queryWrapper.eq(Honor::getPersonId, list.get(i).getPersonId());
//                queryWrapper.eq(Honor::getType, type);
                List<Honor> queryList = iHonorService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(queryList) && queryList.size() > 0) {
                    list.get(i).setId(queryList.get(0).getId());
                }
            }
            iHonorService.saveOrUpdateBatch(list);
        }
    }

    private void getLevel(Honor honor, String prizeName) {
        if (StringUtils.containsAny(prizeName, "国家", "中国")) {
            honor.setPrizeLevel(0);
        } else if (StringUtils.contains(prizeName, "省")) {
            honor.setPrizeLevel(1);
        } else if (StringUtils.contains(prizeName, "市")) {
            honor.setPrizeLevel(2);
        }
        if (StringUtils.contains(prizeName, "特等奖")) {
            honor.setAwardLevel(0);
        } else if (StringUtils.contains(prizeName, "一等奖")) {
            honor.setAwardLevel(1);
        } else if (StringUtils.contains(prizeName, "二等奖")) {
            honor.setAwardLevel(2);
        } else if (StringUtils.contains(prizeName, "三等奖")) {
            honor.setAwardLevel(3);
        }
        honor.setPrizeName(prizeName);
    }

    /**
     * 重要任职/主要任职
     *
     * @param personInfo
     * @param url
     */
    private void parseDuties(PersonInfo personInfo, String url) {
//        url = "https://ysg.ckcest.cn/html/details/subnav/content/621/detail_grxx_zyrz";
        Document doc = CrawlerCommonUtils.getDocument(url);
        if (null == doc)
            return;
        Elements elements = doc.select(".main .content-box .content");
        List<Social> list = new ArrayList<>();
        String date = "";
        String text = "";
        for (Element element : elements) {
            date = element.select(".data").text();
            Elements h4Elements = element.select("h4");
            StringBuilder stringBuilder = new StringBuilder();
            Social social = new Social().builder().personId(personInfo.getId()).build();
            for (int i = 0; i < h4Elements.size(); i++) {
                text = h4Elements.get(i).text();
                if (text.equals(date)) {
                    social.setTenure(text);
//                    map.put("dutiesDate",text);
                } else {
                    if (i == h4Elements.size() - 2) {
                        stringBuilder.append(text);
                        social.setDuties(stringBuilder.toString());
                    } else {
                        stringBuilder.append(text).append(",");
                    }
                }
            }
            list.add(social);
        }

        updateSocial(list);
    }

    private void updateSocial(List<Social> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = list.size() - 1; i >= 0; i--) {
                LambdaQueryWrapper<Social> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(Social::getDuties, list.get(i).getDuties());
                queryWrapper.eq(Social::getPersonId, list.get(i).getPersonId());
                List<Social> queryList = iSocialService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(queryList) && queryList.size() > 0) {
                    list.get(i).setId(queryList.get(0).getId());
                }
            }
            iSocialService.saveOrUpdateBatch(list);
        }
    }

    /***
     * 主要经历
     * @param personInfo
     * @param url
     */
    private void parseExperience(PersonInfo personInfo, String url) {
//        url = "https://ysg.ckcest.cn/html/details/subnav/content/621/detail_grxx_zyjl";
        Document doc = CrawlerCommonUtils.getDocument(url);
        if (null == doc)
            return;
        Elements elements = doc.select(".container .duty");
        List<Social> list = new ArrayList<>();
        for (Element element : elements) {
            Elements h4El = element.select("h4");
            List<String> stringList = new ArrayList<>();
            Social social = new Social().builder().personId(personInfo.getId()).build();
            for (int i = 0; i < h4El.size(); i++) {
                Element h = h4El.get(i);
                String dataText = h.select(".data").text();
                if (StringUtils.isNotBlank(dataText)) {
                    social.setTenure(dataText);
                } else {
                    if (StringUtils.isNotBlank(h.text()))
                        stringList.add(h.text());
                }
                if (i == h4El.size() - 1) {
                    social.setDuties(StringUtils.join(stringList, ","));
                }
            }

            list.add(social);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            // 之前的数据是错误的，先删除
//            LambdaQueryWrapper<Resume> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(Resume::getPersonId, personInfo.getId());
//            iResumeService.remove(queryWrapper);

            updateSocial(list);
        }
    }

    /**
     * 主要学历
     *
     * @param personInfo
     * @param url
     */
    private void parseEducation(PersonInfo personInfo, String url) {
//        url = "https://ysg.ckcest.cn/html/details/subnav/content/621/detail_grxx_zyxl";
        Document doc = CrawlerCommonUtils.getDocument(url);
        if (null == doc)
            return;
        Elements elements = doc.select(".detail_grxx_zyxl .content ul");
        List<Map<String, String>> list = new ArrayList<>();
        for (Element element : elements) {
            Elements liElements = element.select("li");
            Map<String, String> map = new LinkedHashMap<>();
            for (Element liElement : liElements) {
                if (liElement.toString().contains("div")) {
                    String date = liElement.select("h3").text();
                    map.put("educationDate", date);
                } else {
                    Elements h3 = liElement.select("h3");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < h3.size(); i++) {
                        String text = h3.get(i).text();
                        if (i == h3.size() - 1) {
                            stringBuilder.append(text);
                            map.put("education", stringBuilder.toString());
                        } else {
                            stringBuilder.append(text).append(",");
                        }
                    }
                }
            }
            list.add(map);
        }

        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> map = list.get(list.size() - 1);
            if (MapUtils.isNotEmpty(map)) {
                String education = map.get("education");
                if (education.indexOf(",") > 0) {
                    String[] str = education.split(",");
                    if (str.length >= 3) {
                        if (StringUtils.isBlank(personInfo.getSchool()))
                            personInfo.setSchool(str[0]);
                        if (StringUtils.isBlank(personInfo.getMajor()))
                            personInfo.setMajor(str[1]);
                        if (StringUtils.isBlank(personInfo.getAcademicDegree()))
                            personInfo.setAcademicDegree(str[2]);
                    }
                }
            }
        }
        iPersonInfoService.saveOrUpdate(personInfo);

    }

    /**
     * 循环找出需要的院士，获取院士的信息
     */
    public void getPersonalHome() {
        Document doc = CrawlerCommonUtils.getDocument(index);
        Map<String, String> mapUrl = new HashMap();
        mapUrl.put("中国工程院-全体院士", index);
        List<Map> allUrlList = new ArrayList<>();
        Elements UrlElements = doc.getElementById("li_47_parent_00").select("ul li h3 a");
        for (int i = 0; i < UrlElements.size(); i++) {
            Element element = UrlElements.get(i);
            if (i == 5 || i == 6 || i == 7) {
                mapUrl.put(element.text(), url + element.attr("href"));
            }
        }
        allUrlList.add(mapUrl);
        for (Map<String, String> map1 : allUrlList) {
            map1.forEach((key, value) -> {
                // key --> 左侧标题名称     value  --> 标题名称的url地址
                if (StringUtils.containsAny(key, "全体")) {
                    Document doc1 = CrawlerCommonUtils.getDocument(map1.get(key));
                    Elements liElements = doc1.select(".right_md_ysmd").select(".ysxx_namelist.clearfix ul li");
                    parsePersonalData(liElements);
                }
                if (StringUtils.containsAny(key, "已故", "外籍")) {
                    Document doc1 = CrawlerCommonUtils.getDocument(map1.get(key));
                    //获取已故和外籍院士的名字和个人主页地址
                    Elements tdElements = doc1.select(".right_md_ysmd").select(".ysxx_name_tab table tbody tr td");
                    parsePersonalData(tdElements);
                }
            });

        }
    }

    /**
     * 获取工程院院士的名字和个人主页地址
     *
     * @param Elements
     * @return
     */
    private List<Map<String, String>> parsePersonalData(Elements Elements) {
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> nameAndUrlmap = new HashMap<>();
        String name = "";
        String personUrl = "";
        for (Element liElement : Elements) {
            name = liElement.select("a").text();
            personUrl = url + liElement.select("a").attr("href");
            nameAndUrlmap.put(name, personUrl);
        }

        Map<String, String> personalUrlMap = new HashMap<>();
        nameAndUrlmap.forEach((key, value) -> {
            //解析个人详情地址
            Document doc2 = CrawlerCommonUtils.getDocument(value);
            String personalHref = doc2.select(".info_img > a").attr("href");
            if (StringUtils.isNotBlank(key)) {
                personalUrlMap.put(key, personalHref);
            }
        });
        list.add(personalUrlMap);
        return list;
    }

    /**
     * 获取URL中的院士研究方向
     * 从中国工程科技专家库里可以获取到，这里不需要获取了。
     *
     * @param personalUrl url
     * @return
     */
    private String savepersonalInfo(String personalUrl) {
        String researchContents = "";
        Document doc = CrawlerCommonUtils.getDocument(personalUrl);
        Elements allScript = doc.getElementsByTag("script");
        String scriptStr = "";
        for (int i = 0; i < allScript.size(); i++) {
            Element elementScript = allScript.get(i);
            if (StringUtils.contains(elementScript.toString(), "loadingImgContainer")) {
                String loadingImgContainer = elementScript.toString();
                scriptStr = loadingImgContainer.substring(loadingImgContainer.indexOf("["), loadingImgContainer.indexOf("]") + 1);
            }
        }

        if (StringUtils.isNotBlank(scriptStr)) {
            JSONArray jsonArray = JSON.parseArray(scriptStr);
            List<String> list = new ArrayList<>();
            for (Object object : jsonArray) {
                JSONObject jsonObject = JSONObject.parseObject(object.toString());
                list.add(jsonObject.getString("tagName"));
            }
            researchContents = StringUtils.join(list, ",");
        }
        return researchContents;
    }

    private PersonInfo parseIndex(PersonInfo personInfo, String personalUrl) {
        if (null == personInfo)
            personInfo = new PersonInfo();

//        String content = "";
        String imgUrl = "";
        if (personalUrl.contains("http")) {
            Document doc = CrawlerCommonUtils.getDocument(personalUrl);
            List<String> contentList = new ArrayList<>();
            Elements divElements = doc.select(".particular_info2 ul li div");
            // 获取院士馆个人信息
            parseAcademicianHallPersonInfoData(contentList, divElements);
            divElements = doc.select(".bottome_part div");
            // 获取院士馆个人信息
            parseAcademicianHallPersonInfoData(contentList, divElements);
            divElements = doc.select(".acInfo div");
            // 获取院士馆个人信息
            parseAcademicianHallPersonInfoData(contentList, divElements);
            imgUrl = doc.select(".img_fit_cover").attr("src");

//            String text1 = doc.select(".acInfo  div").text();
//            if (StringUtils.isBlank(text1)) {
//                String text = doc.select(".particular_info2 ul li div").text();
//                content = text.replaceAll(": ", ":").replaceAll("院士 ", "院士");
//                imgUrl = doc.select(".img_fit_cover").attr("src");
//            } else {
//                imgUrl = doc.select(".img_fit_cover").attr("src");
//                //姓名:曹喜滨 民族:汉族 性别:男 籍贯:黑龙江省 绥化市 肇东市 出生日期:1963年2月25日
//                String s2 = text1.replaceAll(": ", ":");
//                String text2 = doc.select(".bottome_part div").text();
//                //当选年份:中国工程院院士2019年 学部:机械与运载工程学部 链接:中国工程科技专家库
//                String s4 = text2.replaceAll(": ", ":").replaceAll("院士 ", "院士");
//                //姓名:曹喜滨 民族:汉族 性别:男 籍贯:黑龙江省 绥化市 肇东市 出生日期:1963年2月25日 当选年份:中国工程院院士2019年 学部:机械与运载工程学部 链接:中国工程科技专家库
//                content = s2 + " " + s4;
//            }
            if (CollectionUtils.isNotEmpty(contentList)) {
                for (String content : contentList) {
                    if (content.indexOf(":") > 0) {
                        String[] s = content.split(":");
                        String name = "";
                        String nation = "";
                        String sex = "";
                        String birthplace = "";
                        String birthday = "";
                        String department = "";
                        String nationality = "";
                        String electionYear = "";
                        switch (s[0]) {
                            case "姓名":
                                name = s[1];
                                break;
                            case "民族":
                                nation = s[1];
                                break;
                            case "性别":
                                sex = s[1];
                                break;
                            case "籍贯":
                                birthplace = s[1];
                                break;
                            case "国籍":
                                nationality = s[1];
                                break;
                            case "出生日期":
                                birthday = s[1];
                                break;
                            case "学部":
                                department = s[1];
                                break;
                            case "当选年份":
                                electionYear = s[1].split(" ")[1];
                                break;
                        }


                        //获取选举年
//            Elements divElements = doc.select(".bottome_part div");
//            if (divElements.size() == 0) {
//                divElements = doc.select(".particular_info2 ul li div");
//            }
//            List<String> experienceList = new ArrayList<>();
//            for (Element divElement : divElements) {
//                if (divElement.text().contains("当选年份")) {
//                    Elements h4Elements = divElement.select("h4");
//                    for (Element h4Element : h4Elements) {
//                        if (!h4Element.toString().contains("当选年份")) {
//                            String text = h4Element.text();
//                            String[] s1 = text.split(" ");
//                            StringBuilder stringBuilder = new StringBuilder();
//                            for (int i = s1.length - 1; i >= 0; i--) {
//                                if (i == 0) {
//                                    stringBuilder.append(s1[i]);
//                                }
//                                if (s1[i].contains("年")) {
//                                    stringBuilder.append(s1[i]).append(":");
//                                } else {
//                                    stringBuilder.append(s1[i]).append(";");
//                                }
//                            }
//                            experienceList.add(stringBuilder.toString());
//                        }
//                    }
//                }
//            }
                        //获取链接
                        Elements aElements = doc.select(".bottome_part div").select(".mouseoverClass a");
                        if (aElements.size() == 0) {
                            aElements = doc.select(".particular_info2 ul li div h4 a");
                        }
                        List<Map<String, String>> list = new ArrayList<>();
                        if (aElements.size() > 0) {
                            for (Element aElement : aElements) {
                                Map<String, String> map = new LinkedHashMap<>();
                                map.put("relatedLinksName", aElement.attr("title"));
                                map.put("relatedLinksUrl", aElement.attr("href"));
//                                if (aElement.text().contains("AMiner")) {
//                                    String relatedLinksUrl = aElement.attr("href");
//                                    String relatedLinksName = aElement.text();
//                                    map.put("relatedLinksName", relatedLinksName);
//                                    map.put("relatedLinksUrl", relatedLinksUrl);
//
//                                }
//                                if (aElement.text().contains("中国工程科技专家库")) {
//                                    String relatedLinksUrl = aElement.attr("href");
//                                    String relatedLinksName = aElement.text();
//                                    map.put("relatedLinksName", relatedLinksName);
//                                    map.put("relatedLinksUrl", relatedLinksUrl);
//                                }
//                                if (aElement.text().contains("个人主页")) {
//                                    String relatedLinksUrl = aElement.attr("href");
//                                    String relatedLinksName = aElement.text();
//                                    map.put("relatedLinksName", relatedLinksName);
//                                    map.put("relatedLinksUrl", relatedLinksUrl);
//                                }
                                list.add(map);
                            }
                        } else {
                            log.info("没有其他地址");
                        }

                        if (StringUtils.isNotBlank(name) && StringUtils.isBlank(personInfo.getName()))
                            personInfo.setName(name);
                        if (StringUtils.isNotBlank(nation) && StringUtils.isBlank(personInfo.getNation()))
                            personInfo.setNation(nation);
                        if (StringUtils.isNotBlank(nationality) && StringUtils.isBlank(personInfo.getNationality()))
                            personInfo.setNationality(nationality);
                        if (StringUtils.isNotBlank(sex) && StringUtils.isBlank(personInfo.getSex()))
                            personInfo.setSex(sex);
                        if (StringUtils.isNotBlank(birthplace) && StringUtils.isBlank(personInfo.getBirthplace()))
                            personInfo.setBirthplace(birthplace);
                        if (StringUtils.isNotBlank(birthday) && StringUtils.isBlank(personInfo.getBirthday()))
                            personInfo.setBirthday(birthday);

                        if (StringUtils.isNotBlank(department) && StringUtils.isBlank(personInfo.getDepartment()))
                            personInfo.setDepartment(department);
                        // 当选年
                        if (StringUtils.isNotBlank(electionYear) && StringUtils.isBlank(personInfo.getElectionYear()))
                            personInfo.setElectionYear(electionYear);
                        if (CollectionUtils.isNotEmpty(list)) {
                            personInfo.setRelatedLinks(JSON.toJSONString(list));
                        }
                    }
                }
            }
        }

        iPersonInfoService.saveOrUpdate(personInfo);
        return personInfo;
    }

    /**
     * 获取院士馆个人信息
     *
     * @param contentList
     * @param divElements
     */
    private void parseAcademicianHallPersonInfoData(List<String> contentList, Elements divElements) {
        for (int i = 0; i < divElements.size(); i++) {
            String text = divElements.get(i).text();
            text = text.replaceAll(": ", ":");
            contentList.add(text);
        }
    }


    //获取人生点滴
    public void getResume(PersonInfo personInfo, String url) {
        List<Map<String, String>> lifeList = new ArrayList();
        Document doc = CrawlerCommonUtils.getDocument(url);
        Elements elements = doc.select(".content-box .container .bottome_main .content");
        for (Element element : elements) {
            String text = element.select(" > div").text();
            Map<String, String> map = parseLife(element, text);
            lifeList.add(map);
        }

        if (CollectionUtils.isNotEmpty(lifeList)) {
            List<Resume> resumeList = new ArrayList<>();
            for (Map<String, String> map : lifeList) {
                map.forEach((key, value) -> {
                    Resume resume = new Resume().builder().personId(personInfo.getId()).build();
                    try {
                        resume.setResumeDate(DateUtils.handleDate(key));
                    } catch (Exception e) {
                        resume.setResumeDate(key);
                    }
//                    value = value.replaceAll(",", "").replaceAll("，", "");
                    resume.setResume(value);
                    resumeList.add(resume);
                });
            }
            if (CollectionUtils.isNotEmpty(resumeList)) {
                LambdaQueryWrapper<Resume> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(Resume::getPersonId, personInfo.getId());
                int count = iResumeService.count(lambdaQueryWrapper);
                if (count <= 0)
                    iResumeService.saveOrUpdateBatch(resumeList);
            }
        }
    }

    private Map<String, String> parseLife(Element element, String text) {
        String test1 = text.replaceAll("年 ~", "年~").replaceAll("~ ", "~").replaceAll("  ", " ");
        String[] s1 = test1.split(" ");
        Map<String, String> map = new LinkedHashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        if (s1.length > 1) {
            for (int i = 1; i < s1.length; i++) {
                if (i == s1.length - 1) {
                    stringBuilder.append(s1[i]);
                } else {
                    stringBuilder.append(s1[i]).append(",");
                }
            }
            map.put(s1[0], stringBuilder.toString());
        } else {
            map.put(element.select("h4").text(), element.select(" > div").text());
        }
        return map;
    }


}
